import {Injectable, Inject} from '@angular/core';
import {HttpClient, HttpParams} from '@angular/common/http';
import {Observable} from 'rxjs';
import {map} from 'rxjs/operators';

import {API_CONFIG, ServicesModule} from './services.module';
import {SongUrl, Song} from '../data-types/common.types';

@Injectable({
  providedIn: ServicesModule
})
export class SongService {

  constructor(
    private http: HttpClient,
    @Inject(API_CONFIG) private uri: string
  ) {
  }

  getSongUrl(ids: string): Observable<Array<SongUrl>> {
    const params = new HttpParams().set('id', ids);
    return this.http.get(`${this.uri}/song/url`, {params})
      .pipe(
        map((res: { data: Array<SongUrl> }) => res.data)
      );
  }

  // getSongList(songs: Song | Array<Song>): Observable<Array<Song>> {
  //   const songArr = Array.isArray(songs) ? songs.slice() : [songs];
  //   const ids = songArr.map(item => item.id).join(',');
  //   return Observable.create(observer => {
  //     this.getSongUrl(ids).subscribe(urls => {
  //       observer.next(this.generateSongList(songArr, urls));
  //     });
  //   });
  // }

  getSongList(songs: Song | Array<Song>): Observable<Array<Song>> {
    const songArr = Array.isArray(songs) ? songs.slice() : [songs];
    const ids = songArr.map(item => item.id).join(',');
    return this.getSongUrl(ids).pipe(
      map(urls => this.generateSongList(songArr, urls))
    );
  }

  generateSongList(songs: Array<Song>, urls: Array<SongUrl>): Array<Song> {
    const result = [];
    songs.forEach(song => {
      const url = urls.find(innerUrl => innerUrl.id === song.id).url;
      if (url) {
        result.push({...song, url});
      }
    });
    return result;
  }

}
